package com.wutongyu.mannyburger;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

/**
 * 商品RecyclerView适配器
 * 可提供更好的性能和动画效果
 */
public class ProductRecyclerAdapter extends RecyclerView.Adapter<ProductRecyclerAdapter.ProductViewHolder> {

    private final Context context;
    private final List<Product> productList;
    private final CartManager cartManager;
    private Animation quantityChangeAnimation;
    
    /**
     * 构造函数
     */
    public ProductRecyclerAdapter(Context context, List<Product> productList) {
        this.context = context;
        this.productList = productList;
        this.cartManager = CartManager.getInstance();
        this.quantityChangeAnimation = AnimationUtils.loadAnimation(context, android.R.anim.fade_in);
    }

    @NonNull
    @Override
    public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.product_list_item, parent, false);
        return new ProductViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ProductViewHolder holder, int position) {
        Product product = productList.get(position);
        
        // 设置商品信息
        holder.productNameTextView.setText(product.getName());
        holder.productPriceTextView.setText("¥" + product.getPrice());
        
        // 设置商品描述（如果有）
        if (product.getDescription() != null && !product.getDescription().isEmpty()) {
            holder.productDescriptionTextView.setText(product.getDescription());
            holder.productDescriptionTextView.setVisibility(View.VISIBLE);
        } else {
            holder.productDescriptionTextView.setVisibility(View.GONE);
        }
        
        // 设置商品图片（如果有）
        if (product.getImageResId() != 0) {
            holder.productImageView.setImageResource(product.getImageResId());
        } else {
            holder.productImageView.setImageResource(R.drawable.bg); // 默认图片
        }
        
        // 从购物车中获取当前商品的数量
        CartItem cartItem = findCartItemByProduct(product);
        if (cartItem != null) {
            product.setQuantity(cartItem.getQuantity());
        } else {
            product.setQuantity(0);
        }
        
        // 更新数量显示
        updateQuantityDisplay(holder, product);
        
        // 设置增加按钮点击事件
        holder.btnIncrease.setOnClickListener(v -> {
            int quantity = product.getQuantity();
            product.setQuantity(quantity + 1);
            
            // 更新购物车
            cartManager.addToCart(product);
            
            // 更新UI
            updateQuantityDisplay(holder, product);
            // 应用动画
            holder.productQuantityTextView.startAnimation(quantityChangeAnimation);
        });
        
        // 设置减少按钮点击事件
        holder.btnDecrease.setOnClickListener(v -> {
            int quantity = product.getQuantity();
            if (quantity > 0) {
                product.setQuantity(quantity - 1);
                
                // 更新购物车
                if (product.getQuantity() == 0) {
                    cartManager.removeFromCart(product);
                } else {
                    cartManager.updateCartItemQuantity(product);
                }
                
                // 更新UI
                updateQuantityDisplay(holder, product);
                // 应用动画
                holder.productQuantityTextView.startAnimation(quantityChangeAnimation);
            }
        });
        
        // 设置商品项点击事件，跳转到商品详情页
        holder.itemView.setOnClickListener(v -> {
            Intent intent = new Intent(context, ProductDetailActivity.class);
            intent.putExtra("product_id", product.getId());
            context.startActivity(intent);
        });
    }
    
    private void updateQuantityDisplay(@NonNull ProductViewHolder holder, Product product) {
        int quantity = product.getQuantity();
        holder.productQuantityTextView.setText(String.valueOf(quantity));
        
        if (quantity > 0) {
            holder.btnDecrease.setVisibility(View.VISIBLE);
        } else {
            holder.btnDecrease.setVisibility(View.GONE);
        }
    }
    
    /**
     * 查找商品在购物车中的项
     */
    private CartItem findCartItemByProduct(Product product) {
        List<CartItem> cartItems = cartManager.getCartItems();
        for (CartItem item : cartItems) {
            if (item.getProduct() != null && 
                item.getProduct().getId() == product.getId()) {
                return item;
            }
        }
        return null;
    }

    @Override
    public int getItemCount() {
        return productList.size();
    }

    /**
     * 更新商品列表
     */
    public void updateProductList(List<Product> newProducts) {
        if (newProducts == null) {
            Log.d("ProductRecyclerAdapter", "updateProductList: newProducts为null，不更新列表");
            return;
        }
        
        Log.d("ProductRecyclerAdapter", "updateProductList: 开始更新商品列表，当前列表大小:" + 
              productList.size() + "，新列表大小:" + newProducts.size());
        
        // 使用DiffUtil计算列表差异并更新
        DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new DiffUtil.Callback() {
            @Override
            public int getOldListSize() {
                return productList.size();
            }

            @Override
            public int getNewListSize() {
                return newProducts.size();
            }

            @Override
            public boolean areItemsTheSame(int oldPosition, int newPosition) {
                return productList.get(oldPosition).getId() == 
                       newProducts.get(newPosition).getId();
            }

            @Override
            public boolean areContentsTheSame(int oldPosition, int newPosition) {
                Product oldProduct = productList.get(oldPosition);
                Product newProduct = newProducts.get(newPosition);
                return oldProduct.getName().equals(newProduct.getName()) &&
                       oldProduct.getPrice() == newProduct.getPrice() &&
                       (oldProduct.getDescription() == null ? 
                        newProduct.getDescription() == null : 
                        oldProduct.getDescription().equals(newProduct.getDescription()));
            }
        });
        
        Log.d("ProductRecyclerAdapter", "updateProductList: 清空当前列表并添加新元素");
        try {
            // 安全地替换列表内容，避免直接清空
            synchronized (productList) {
                productList.clear();
                productList.addAll(newProducts);
            }
            
            Log.d("ProductRecyclerAdapter", "updateProductList: 更新完成，当前列表大小:" + productList.size());
            
            // 确保在主线程上通知更新
            if (context instanceof android.app.Activity) {
                android.app.Activity activity = (android.app.Activity) context;
                activity.runOnUiThread(() -> {
                    // 使用DiffUtil分发更新通知
                    diffResult.dispatchUpdatesTo(this);
                    // 额外记录一次成功通知的日志
                    Log.d("ProductRecyclerAdapter", "成功在UI线程上通知适配器更新");
                });
            } else {
                // 如果上下文不是Activity，则直接通知
                diffResult.dispatchUpdatesTo(this);
            }
        } catch (Exception e) {
            Log.e("ProductRecyclerAdapter", "更新列表时发生异常: " + e.getMessage());
            e.printStackTrace();
            
            // 异常恢复：直接重置列表并刷新
            try {
                productList.clear();
                productList.addAll(newProducts);
                notifyDataSetChanged();
                Log.d("ProductRecyclerAdapter", "已使用notifyDataSetChanged()恢复");
            } catch (Exception ex) {
                Log.e("ProductRecyclerAdapter", "恢复更新时也发生异常: " + ex.getMessage());
            }
        }
    }
    
    /**
     * 重置所有商品的数量显示
     * 在购物车被清空后调用此方法，确保所有商品的数量显示正确更新为0
     */
    public void resetAllQuantityDisplays() {
        // 通知所有商品项刷新显示
        notifyDataSetChanged();
    }

    /**
     * 商品列表项ViewHolder
     */
    static class ProductViewHolder extends RecyclerView.ViewHolder {
        ImageView productImageView;
        TextView productNameTextView;
        TextView productDescriptionTextView;
        TextView productPriceTextView;
        TextView productQuantityTextView;
        ImageButton btnDecrease;
        ImageButton btnIncrease;

        public ProductViewHolder(@NonNull View itemView) {
            super(itemView);
            productImageView = itemView.findViewById(R.id.product_image);
            productNameTextView = itemView.findViewById(R.id.product_name);
            productDescriptionTextView = itemView.findViewById(R.id.product_description);
            productPriceTextView = itemView.findViewById(R.id.product_price);
            productQuantityTextView = itemView.findViewById(R.id.product_quantity);
            btnDecrease = itemView.findViewById(R.id.btn_decrease);
            btnIncrease = itemView.findViewById(R.id.btn_increase);
        }
    }
} 